package com.cqxyd.smartsite.util;

import com.cqxyd.smartsite.pojo.AttendanceDownloadDetial;
import com.cqxyd.smartsite.pojo.AttendanceDownloadInfo;
import com.cqxyd.smartsite.pojo.UploadResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Angus Yu
 * @date 2020-06-20 16:37
 */
@Service
public class GetHelper {
    //private  Logger logger = Logger.getLogger(PostHelper.class);
    private final Logger logger = LoggerFactory.getLogger(GetHelper.class);
    @Value("${base_url}")
    private String baseUrl;

    @Value("${supplier_key_id}")
    private String supplierKeyId;

    @Value("${supplier_key_secret}")
    private String supplierKeySecret;

    @Value("${attendance_download_url}")
    private String attendanceDownloadUrl;
    @Value("${access_token}")
    private String accessToken;
    @Value("${project_worker_url}")
    private String projectWorkerUrl;

    private JSONResult<String> getRequest(String URL, String programKeyId, String programKeySecret) {
        String jsonString = "";
        try {

            // 1. 取发送请求时取服务器的UNIX时间戳（服务器时间需要提前与标准时间进行校对），例如：1526438202
            String unixTimeStr = Long.toString(System.currentTimeMillis() / 1000L);
            // 2.
            // 生成一个随机字符串，长度至少10位，由英文字符与数字组成，如：jUY9ybWcM3DH，注意随机字符串每次请求都要不同，不要在不同请求中使用相同随机字符串。
            String randomStr = UUID.randomUUID().toString().replaceAll("\\-", "").toUpperCase();
            // 3. 使用下划线将随机字符串，时间戳与密钥(供应商密钥在前项目密钥在后)拼接为预处理字符串：
            // jUY9ybWcM3DH_1526438202_Ny35o694RgXURrNQ7hCBbI4wyearCWxx7H4n_
            // RMSRvZBhviBiWlddbXil5EqVQhkHJ0WJUbH7
            String preStr = randomStr + "_" + unixTimeStr + "_" + supplierKeySecret + "_"
                    + programKeySecret;
            // 4. 使用sha1
            // Hash算法对预处理字符串进行加密，得到的结果即为签名后的字符串：e914fed7db86318b6d8ce01a6f7cfe463c929f3d
            String signature = DigestUtils.sha1Hex(preStr);
            URL url = new URL(baseUrl + URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            // 5.将密钥的keyId，随机字符串（rCode），计算签名时的UNIX时间戳以及签名放入http请求的头部,格式为：[供应商keyId]_[项目keyId]，
            // 与数据一起发送给重庆市两江新区智慧工地信息管理平台数据接口。此时HTTP请求头中包含的签名信息如下：
            // keyId=e6fe9dd5-58af-11e8-857d-00163e32d704_1b0f28a4-a5a8-4ea8-ae1a-3b80d6e72397（授权id,以下划线连接，供应商的在前，项目的在后）
            // ts=1526438202（时间戳）
            // rCode= jUY9ybWcM3DH (随机字符串)
            // signature= e914fed7db86318b6d8ce01a6f7cfe463c929f3d（密钥签名）
            connection.setRequestProperty("keyId", supplierKeyId + "_" + programKeyId);
            connection.setRequestProperty("ts", unixTimeStr);
            connection.setRequestProperty("rCode", randomStr);
            connection.setRequestProperty("signature", signature);
            connection.connect();
            StringBuffer buffer = new StringBuffer();
            if (200 == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String str = null;
                while ((str = br.readLine()) != null) {
                    buffer.append(str);
                }
                br.close();
                isr.close();
                is.close();
                jsonString = buffer.toString();

            } else {
                return JSONResult.errorMsg("GET获取信息失败，返回代码："+connection.getResponseCode());
            }

        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        }
        return JSONResult.ok(jsonString);
    }


    /**
     * 发送普通请求
     *
     * @param URL 地址
     * @return
     */
    private JSONResult<String> get(String URL) {
        String jsonString = "";
        try {
            StringBuffer buffer = new StringBuffer();
            try {
               // String testUrl = "http://110.80.38.74:8034/api/transaction/listAttTransaction?startDate=2020-07-01%2017%3A57%3A40&endDate=2020-07-05%2017%3A57%3A40&pageNo=1&pageSize=100&access_token="+accessToken;
                URL url = new URL(URL);
                HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
                //System.out.println(urlCon.getResponseCode());
                urlCon.connect();
                if (200 == urlCon.getResponseCode()) {
                    InputStream is = urlCon.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is, "utf-8");
                    BufferedReader br = new BufferedReader(isr);
                    String str = null;
                    while ((str = br.readLine()) != null) {
                        buffer.append(str);
                    }
                    br.close();
                    isr.close();
                    is.close();
                    jsonString = buffer.toString();

                } else {
                    return JSONResult.errorMsg("GET获取信息失败，返回代码："+urlCon.getResponseCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                return JSONResult.errorMsg(e.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        }
        return JSONResult.ok(jsonString);
    }

    /**
     * 下载人员考勤信息
     *
     * @param startTime  开始时间
     * @param endTime 结束时间
     * @return
     */
    public JSONResult<List<AttendanceDownloadDetial>> getAttendanceRecord(Integer pageNo, Integer pageSize, Date startTime, Date endTime) {
        if (pageNo<=0){
            return  JSONResult.errorMsg("页码pageIndex必须大于0");
        }
        if (pageSize<=0 || pageSize>1000){
            return  JSONResult.errorMsg("每页条数pageSize必须大于0，小于等于1000");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTimeStr = sdf.format(startTime).replace(" ","%20").replace(":","%3A");
        String endTimeStr = sdf.format(endTime).replace(" ","%20").replace(":","%3A");
        String url = MessageFormat.format("{0}?startDate={1}&endDate={2}&pageNo={3}&pageSize={4}" +
                "&access_token={5}",attendanceDownloadUrl,startTimeStr,endTimeStr,pageNo,pageSize,accessToken);

        JSONResult<String> result = get(url);
        if (!result.isOK()) return JSONResult.errorMsg(result.getMsg());

        ObjectMapper mapper = new ObjectMapper();
        try {
            AttendanceDownloadInfo attendanceDownloadInfo = mapper.readValue(result.getData(), AttendanceDownloadInfo.class);
            if ("0".equals(attendanceDownloadInfo.getCode())){
                return JSONResult.ok(attendanceDownloadInfo.getData());
            }else  {
                logger.error(attendanceDownloadInfo.getMessage());
                return JSONResult.errorMsg(attendanceDownloadInfo.getMessage());
            }
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        }
    }


    /**
     * 下载人员信息
     *
     * @param programKeyId     项目编码
     * @param programKeySecret 项目密匙
     * @param page             页码
     * @return
     */
    public JSONResult<String> downLoadProjectWorker(String programKeyId, String programKeySecret,
                                                    Integer page) {
        ObjectMapper mapper = new ObjectMapper();
        String postResult;
        try {
            JSONResult<String> result = getRequest(projectWorkerUrl+"?page="+page,programKeyId,programKeySecret);
            if (!result.isOK()) return result;
            postResult = result.getData();

           /* if (!StringUtils.isEmpty(postResult)) {
                UploadResult uploadResult = mapper.readValue(postResult, UploadResult.class);
                if (!"0".equals(uploadResult.getCode())) {
                    return getErrorJSONResult(uploadResult);
                }
            } else {
                String info = "postRequest返回了空值，发送信息：" + record;
                logger.error(info);
                return JSONResult.errorMsg("postRequest返回了空值");
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return JSONResult.errorMsg(e.getMessage());
        }

        return JSONResult.ok("下载人员信息成功：" + postResult);
    }
}
